#!/usr/bin/python3

# 微单照片重命名脚本

from crtime import get_crtimes_in_dir
import time
import os


def rename():
    for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
        filename = fname.split('/')[1]
        if filename.startswith('.') or not (filename.endswith('.JPG') or filename.endswith('.MP4')):
            continue

        end_name = '.JPG' if filename.endswith('.JPG') else '.MP4'
        new_name = time.strftime("DSC_%Y%m%d_%H%M%S", time.localtime(date)) + end_name
        print("开始处理文件：%s，新文件名为：%s" % (filename, new_name))

        while new_name in os.listdir(os.getcwd()):
            add_name = int(new_name.split('_')[2].split('.')[0]) + 1
            new_name = new_name[0:new_name.rindex('_') + 1] + str(add_name) + end_name
            print("文件名已存在，+1：", new_name)

        os.rename(filename, new_name)
        print("文件：%s 已重命名为：%s \n" % (filename, new_name))


if __name__ == '__main__':
    print("开始重命名文件...\n")
    rename()
